package com.example.http;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;

public class HttpClinetUtil {
    private static final String CHARSET = "UTF-8";

    public static String doGet(String url) {//写好测试一下
        CloseableHttpClient client = HttpClients.createDefault();
        URIBuilder uriBuilder = null;
        String str = null;
        try {
            uriBuilder = new URIBuilder(url);
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            //5,设置请求报文头部的编码
            httpGet.setHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
            //6,设置期望服务返回的编码
            httpGet.setHeader(new BasicHeader("Accept", "text/plain;charset=utf-8"));//写好后换成application、json试试
            //7，请求服务
            CloseableHttpResponse response = null;
            response = client.execute(httpGet);
            //8，获取请求返回码
            int statusCode = response.getStatusLine().getStatusCode();
            //9如果请求返回码是200，则说明请求成功
            if (statusCode < 400) {
                //10,获取返回实体
                HttpEntity entity = response.getEntity();
                //11,通过EntityUtils的一个工具类获取返回的内容
                str = EntityUtils.toString(entity,"utf-8");//需要加，不然乱码
                System.out.println("请求成功的返回内容：" + str);
            } else {
                System.out.println("请求失败！");
            }
            response.close();
            client.close();
            return str;
        } catch (URISyntaxException e) {
            e.printStackTrace();
            System.out.println(" 对于包含特殊字符的url会抛出urisyntaxexception异常");
        } catch (IOException e) {
            System.out.println("发送请求失败");
            e.printStackTrace();
        }
        return str;
    }
}


